package com.streamsets.datacollector.pileline.stage;

import com.streamsets.datacollector.pileline.enums.HiveMetadataEnum;
import com.streamsets.datacollector.restapi.bean.ConfigConfigurationJson;
import com.streamsets.datacollector.restapi.bean.StageConfigurationJson;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 初始化HiveMetastore查询配置
 * @author wengzhonghui
 * @date 2020/05/30 19:12
 */
public class InitHiveMetastoreConfig {

    /*
     * hive Metastore stage名称
     */
    public static final String STAGE_HIVE_QUERY_NAME = "HiveMetastore_01";
    // jdbcURL的配置属性名
    public static final String STAGE_CONF_N_HIVE_JDBC_URL = "conf.hiveConfigBean.hiveJDBCUrl";

    public static void init(StageConfigurationJson stage, String defaultHiveJdbcUrl){

        if(STAGE_HIVE_QUERY_NAME.equalsIgnoreCase(stage.getInstanceName())) {
            if (StringUtils.isNotBlank(defaultHiveJdbcUrl)) {
                List<ConfigConfigurationJson> configs = intConfig(stage.getConfiguration(), defaultHiveJdbcUrl);
                stage.setConfiguration(configs);
            }
        }
    }

    public static List<ConfigConfigurationJson> intConfig(List<ConfigConfigurationJson> oldConfigs
            , String defaultHiveJdbcUrl){
        List<ConfigConfigurationJson> newConfigs = new ArrayList<>();
        for(ConfigConfigurationJson config :oldConfigs ){
            config = initHiveJDBCUrl(config, defaultHiveJdbcUrl);
            config = initHiveDriver(config);
            newConfigs.add(config);
        }
        return newConfigs;
    }


    // 初始化hiveJdbc连接
    private static ConfigConfigurationJson initHiveJDBCUrl(ConfigConfigurationJson config, String defaultHiveJdbcUrl){
        if(STAGE_CONF_N_HIVE_JDBC_URL.equalsIgnoreCase(config.getName())){
            config = new ConfigConfigurationJson(STAGE_CONF_N_HIVE_JDBC_URL,defaultHiveJdbcUrl);
        }
        return config;
    }

    // 初始化hive驱动
    private static ConfigConfigurationJson initHiveDriver(ConfigConfigurationJson config){
        if(HiveMetadataEnum.hiveJDBCDriver.getName().equalsIgnoreCase(config.getName())){
            config = new ConfigConfigurationJson(HiveMetadataEnum.hiveJDBCDriver.getName()
                    ,HiveMetadataEnum.hiveJDBCDriver.getDefaultValue());
        }
        return config;
    }


}
